//
//  YCCoreMotionViewController.m
//  DemoShake
//
//  Created by 唐可雄 on 16/8/30.
//  Copyright © 2016年 swustyc. All rights reserved.
//

#import "YCCoreMotionViewController.h"

#import <CoreMotion/CoreMotion.h>

@interface YCCoreMotionViewController ()

/// 动作管理器
@property (strong, nonatomic) CMMotionManager *manager;

@end

@implementation YCCoreMotionViewController

#pragma mark - Life Cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.manager.isAccelerometerAvailable) {
        // 加速计可用
        [self.manager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
            // 当采样到加速计信息时就会执行
            if (error) {
                return;
            }
            
            CMAcceleration acceleration = accelerometerData.acceleration;
            self.textView.text = [self.textView.text stringByAppendingString:[NSString stringWithFormat:@"x:%f y:%f z:%f\n", acceleration.x, acceleration.y, acceleration.z]];
        }];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"加速计不可用" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
}

#pragma mark - Setter and Getter

- (CMMotionManager *)manager {
    if (_manager == nil) {
        _manager = [[CMMotionManager alloc] init];
        
        // 1秒采集1次
        _manager.accelerometerUpdateInterval = 1./1.;
    }
    
    return _manager;
}

#pragma mark - IBAction

- (IBAction)clearBtnDidClick:(id)sender {
    self.textView.text = nil;
}

@end
